package com.yinhai.httpclient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public final class HttpClientMethod {
	
	public static String PostMethod(String remoteUrl, List<? extends NameValuePair> nvps) throws Exception {	
		String htmlContent = null;
		
		if(remoteUrl == null || remoteUrl.equals("")) {
			Exception e = new Exception("url string is null.");
			throw e;
		}
		HttpClient httpClient = HttpClientManager.GetInstance().createHttpClient();
		if(httpClient == null) {
			Exception e = new Exception("Create HttpClient Object fail.");
			throw e;
		} 

		HttpPost post = new HttpPost(remoteUrl);
		post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
		try {
			if(nvps != null) {
				post.setEntity(new UrlEncodedFormEntity(nvps, HttpProtocolParams.getHttpElementCharset(httpClient.getParams())));
			}
			HttpResponse rsp = httpClient.execute(post);
			
			HttpEntity entity = rsp.getEntity();
			htmlContent = new String(EntityUtils.toByteArray(entity), HttpProtocolParams.getContentCharset(httpClient.getParams()));
	        if(entity != null) {
	        	try {
	        		entity.consumeContent();
	        	} catch(IOException ei) {	}
	        }
		} catch(UnsupportedEncodingException uee) {
			throw uee;			
		} catch(ClientProtocolException cpe) {
			throw cpe;
		} catch(IOException ioe) {
			throw ioe;
		} 
		
		return htmlContent;
	}
	
	public static byte[] GetBinary(String remoteUrl) throws Exception {	
		byte[] bytes = null;
		
		if(remoteUrl == null || remoteUrl.equals("")) {
			Exception e = new Exception("url string is null.");
			throw e;
		}
		
		HttpClient httpClient = HttpClientManager.GetInstance().createHttpClient();
		if(httpClient == null) {
			Exception e = new Exception("Create HttpClient Object fail.");
			throw e;
		} 
		
		HttpGet req = new HttpGet(remoteUrl);
		try {
			HttpResponse rsp = httpClient.execute(req);
			HttpEntity entity = rsp.getEntity();
			bytes = EntityUtils.toByteArray(entity);
	        if (entity != null) {
	        	try {
	        		entity.consumeContent();
	        	} catch(IOException ei) {	}
	        }
		} catch(ClientProtocolException cpe) {
			throw cpe;
		} catch(IOException ioe) {
			throw ioe;
		} 
		return bytes;
	}

}
